<?php
/**
 * Extends SimpleXML to add valuable functionality to SimpleXMLElement class
 * 
 * @category   Epic
 * @package    Epic_Simplexml
 * @author     Epic Core Team <rukanhitokiri@gmail.com>
 */
class Epic_Simplexml_Element extends SimpleXMLElement
{
    /**
     * Return node find by xpath expression
     *
     * @param string $xpath
     * @return Epic_Simplexml_Element
     */
    public function getXpath($xpath)
    {
        $arr = $this->xpath($xpath);
        $node = $arr[0];
        return $node;
    }
    
    /**
     * Trả lại nút cha của nút đang tham chiếu đến sử dụng xpath
     *
     * @return Varien_Simplexml_Element
     */
    public function getParent()
    {
    	$arr = $this->xpath('..');
    	$parent = $arr[0];
    	return $parent;
    }
    
    /**
     *
     *
     * @param Varien_Simplexml_Element $source
     * @return Varien_Simplexml_Element
     */
    public function removeChild($source)
    {
    	$domRef = dom_import_simplexml($source);
    	$domRef->parentNode->removeChild($domRef);
    	return $this;
    }
    
    /**
     * Gắn thêm một nút vào cho nút tồn tại
     *
     * @param SimpleXMLElement $source
     * @return SimpleXMLElement
     */
    public function appendChild($source)
    {
    	// Add a node
    	if ($source->children()) {
    		// name of the source node
    		$name = $source->getName();
    		$child = $this->addChild($name);
    	}
    	// Add attribute for node
    	$attributes = $source->attributes();
    	foreach ($attributes as $key => $value) {
    		$child->addAttribute($key, $value);
    	}
    
    	foreach ($source->children() as $sourceChild) {
    		$child->appendChild($sourceChild);
    	}
    	return $this;
    }
}
